<template> 
  <div class="qq-chat-wrapper"> 
    <div class="background-overlay"></div>
    <div class="qq-chat-container"> 
      <div class="qq-chat-header"> 
        <button type="button" class="back-btn" @click="goBack">返回</button>
        <h2>与{{ friendName }}畅聊 </h2> 
      </div> 
      <div class="qq-chat-area"> 
        <div class="qq-message-list" ref="messageList"> 
          <div v-for="(message, index) in messages" :key="index" :class="['qq-message', message.sender === currentUser ? 'self' : 'other']">
            <!-- 自己发送的消息 -->
            <div v-if="message.sender === currentUser" class="message-item">
              <div class="qq-message-content">
                <span class="qq-sender">{{ message.sender }}</span> 
                <span class="qq-content">{{ message.content }}</span> 
              </div>
            </div>
            <!-- 好友发送的消息 -->
            <div v-else class="message-item">
              <div class="qq-message-content">
                <div class="qq-sender">{{ message.sender }}</div>
                <div class="qq-content">{{ message.content }}</div>
              </div>
            </div>
          </div> 
        </div> 
      </div> 
      <div class="qq-input-group"> 
        <button @click="toggleEmojiPanel" class="emoji-btn">😀</button>
        <input type="text" id="messageInput" v-model="newMessage" @keyup.enter="sendMessage" placeholder="输入消息..." />
        <button type="button" class="qq-submit-btn" @click="sendMessage">
          发送
        </button>
        <div v-if="showEmojiPanel" class="emoji-panel">
          <span v-for="emoji in emojis" :key="emoji" @click="insertEmoji(emoji)" class="emoji-item">
            {{ emoji }}
          </span>
        </div>
      </div> 
    </div> 
  </div> 
</template>

<script>
import { useUserStore } from '@/stores/userStore'
import websocket from '@/services/websocket'; 
import { storePrivateMessage, getChatKey } from '@/stores/messageStorage'

export default {
    data() {
        const userStore = useUserStore()
        return {
            currentUser: userStore.username || '当前用户名',
            messages: [],
            newMessage: '',
            friendName: this.$route.params.friendName || '好友用户名',
            socket: null,
            messageListener: null,
            messageCheckInterval: null,
            showEmojiPanel: false,
            emojis: [
                '😀', '😂', '😍', '😭', '😡', '👍', '🙏', '🎉', '❤️', '😎',
                '🥰', '😅', '😢', '🤔', '🤯', '👏', '😴', '💯', '🔥', '💡'
            ]
        };
    },
    mounted() {
        // 初始化WebSocket连接
        this.socket = websocket.initWebSocket();
        
        // 设置全局消息处理函数
        websocket.setGlobalMessageHandler((message) => {
            if (message.messageType === 4 && 
                (message.receiver === this.currentUser || message.sender === this.friendName)) {
                storePrivateMessage(message);
                this.loadHistoryMessages();
            }
        });

        // 加载历史消息
        this.loadHistoryMessages();
        
        // 监听路由变化
        this.$watch(
            () => this.$route.params.friendName,
            (newFriendName) => {
                if (newFriendName) {
                    this.friendName = newFriendName;
                    this.loadHistoryMessages();
                }
            }
        );
        
        // 设置全局消息监听器
        this.setupMessageListener();
        // 启动消息检查定时器
        this.messageCheckInterval = setInterval(() => {
            this.loadHistoryMessages();
        }, 1000); // 每秒检查一次
    },

    beforeUnmount() {
        if (this.messageListener) {
            window.removeEventListener('newPrivateMessage', this.messageListener);
        }

        if (this.messageCheckInterval) {
            clearInterval(this.messageCheckInterval);
        }
    },
    methods: {
        sendMessage() {
            if (this.newMessage.trim()) {
                if (this.socket && this.socket.readyState === WebSocket.OPEN) {
                    const message = {
                        messageType: 4,
                        sender: this.currentUser,
                        receiver: this.friendName,
                        content: this.newMessage
                    };
                    this.socket.send(JSON.stringify(message));
                    
                    storePrivateMessage(message);
                    this.loadHistoryMessages();
                    this.newMessage = '';
                }
            }
        },
        scrollToBottom() {
            this.$nextTick(() => {
                if (this.$refs.messageList) {
                    this.$refs.messageList.scrollTop = this.$refs.messageList.scrollHeight;
                }
            });
        },
        goBack() {
            this.$router.push({ name: 'main' });
        },

        setupMessageListener() {
            this.messageListener = (event) => {
                const { chatKey, message } = event.detail;
                const currentChatKey = getChatKey(this.currentUser, this.friendName);
                
                if (chatKey === currentChatKey) {
                    // 重新加载所有消息确保数据一致
                    this.loadHistoryMessages();
                }
            };
            
            window.addEventListener('newPrivateMessage', this.messageListener);
        },
        
        loadHistoryMessages() {
            const messages = JSON.parse(localStorage.getItem('privateMessages') || '{}');
            const chatKey = getChatKey(this.currentUser, this.friendName);
            
            if (messages[chatKey]) {
                // 按时间戳排序消息
                this.messages = messages[chatKey].sort((a, b) => a.timestamp - b.timestamp);
                this.$nextTick(() => {
                    if (this.$refs.messageList) {
                        this.$refs.messageList.scrollTop = this.$refs.messageList.scrollHeight;
                    }
                });
            }
        },
        toggleEmojiPanel() {
            this.showEmojiPanel = !this.showEmojiPanel;
        },
        insertEmoji(emoji) {
            this.newMessage += emoji;
            this.showEmojiPanel = false;
        },
    },
};
</script>


<style scoped>
.qq-chat-wrapper {
  min-height: 100vh;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-image: url("@/assets/re_bg.png");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-color: #f0f2f5;
  position: absolute;
  top: 0;
  left: 0;
}

.qq-chat-container {
  width: 100%;
  max-width: 800px;
  height: 600px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.qq-chat-header {
  padding: 15px 20px;
  border-bottom: 1px solid #e8e8e8;
  position: relative;
}

.back-btn {
  position: absolute;
  top: 15px;
  right: 20px;
  padding: 10px 20px;
  background-color: #1abc9c;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  font-weight: bold;
  transition: background-color 0.3s, transform 0.2s;
}

.back-btn:hover {
  background-color: #16a085;
  transform: translateY(-5px);
}

.back-btn:active {
  background-color: #1abc9c;
  transform: translateY(2px);
}

.qq-submit-btn {
  padding: 12px 20px;
  background-color: #1abc9c;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  font-weight: bold;
  transition: background-color 0.3s, transform 0.2s;
  white-space: nowrap;
}

.qq-submit-btn:hover {
  background-color: #16a085;
  transform: translateY(-5px);
}

.qq-submit-btn:active {
  background-color: #1abc9c;
  transform: translateY(2px);
}
.qq-chat-area {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #f5f6f7;
}

.qq-message-list {
  display: flex;
  flex-direction: column;
}

.qq-message {
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;
}

.qq-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.qq-message.self {
  flex-direction: row-reverse;
}

.self-avatar {
  margin-left: 10px;
  margin-right: 0;
}

.other-avatar {
  margin-right: 10px;
  margin-left: 0;
}

.message-item {
  display: flex;
  align-items: flex-start;
}

.qq-message-content {
  width: 300px;
  min-height: 40px;
  max-height: 300px;
  padding: 10px 15px;
  border-radius: 6px;
  position: relative;
  background-color: white;
  overflow-y: auto;
  word-wrap: break-word;
  white-space: pre-wrap;
}

.qq-message.self .qq-message-content {
  margin-left: auto;
  background-color: white;
}

.qq-message.other .qq-message-content {
  background-color: white;
}

.qq-sender {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
  display: block;
  font-weight: bold; 
}

.qq-content {
  display: block;
  margin-top: 5px;
}
.qq-input-group {
  display: flex;
  width: 100%;
  padding: 10px;
  background-color: white;
  border-top: 1px solid #e8e8e8;
}

.qq-input-group input {
  flex: 1;
  padding: 10px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  margin-right: 10px;
}
.emoji-btn {
  background: none;
  border: none;
  font-size: 22px;
  cursor: pointer;
  margin-right: 10px;
}

.emoji-panel {
  position: absolute;
  bottom: 60px;
  left: 20px;
  background: white;
  border: 1px solid #ccc;
  border-radius: 8px;
  padding: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
  z-index: 10;
}

.emoji-item {
  cursor: pointer;
  font-size: 20px;
}
</style>